import React, {useEffect, useRef, useState} from 'react';

// @ts-ignore
import {CapsuleChart} from '@jiaminghi/data-view-react';
import PageContainer from "@ant-design/pro-layout/es/components/PageContainer";
import "./index.css";
import {AutoComplete, Button, Card, Checkbox, Form, Modal, Spin} from "antd";
import {ProFormDateRangePicker, QueryFilter} from "@ant-design/pro-form";
import ProTable, {ActionType} from '@ant-design/pro-table';
import {useRequest} from "@@/plugin-request/request";
import {dateFormat, deleteOfJsonArrays, downloadFile, hooksSet, paramsChange} from "@/assets/utils/utils";
import {
  allUrl,
  exportExcel,
  listChildren,
  sum,
  sumByCity,
  sumByCityAndDay,
  sumByDay
} from "@/pages/analysis/PageAnalysis/service";
// @ts-ignore
import $ from 'jquery';
import {getDateString} from "@/assets/utils/dateUtils";
import moment from "moment";
import {getOption, initECharts} from "@/assets/utils/eChartsUtils";

import {PageAnalysis} from "@/pages/analysis/PageAnalysis/data";

const PageAnalysisTools: React.FC<{}> = () => {

  const [spinning, setSpinning] = useState(false)
  const [exportDisabled, setExportDisabled] = useState(false)
  const [listChildrenLoading, setListChildrenLoading] = useState(true)
  const actionRef = useRef<ActionType>();
  const cityActionRef = useRef<ActionType>();
  const fuzzyMatchingActionRef = useRef<ActionType>();
  const [form] = Form.useForm();
  form.setFieldsValue(Object.assign({}, {
    url: "https://wap.jx.10086.cn/hui/login/otherLogin",
    dateRange: [getDateString("yyyyMM") + "01", getDateString("yyyyMMdd")],
    // url: "wap.jx.10086.cn/hui/release/goods/8755/index.html",
    // dateRange: ['20210425', '20210426'],
    current: 1,
    size: 10
  }, form.getFieldsValue()))
  /**
   * 已选择的匹配链接
   */
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [selectedRows, setSelectedRows] = useState([]);
  /**
   * 参数筛选弹框
   */
  const [modelVisible, setModelVisible] = useState(false)
  const [mergeLinksModelVisible, setMergeLinksModelVisible] = useState(false)
  /**
   * 表数据
   */
  const [data, setData] = useState([]);
  /**
   * 地市维度表数据
   */
  const [cityData, setCityData] = useState([]);
  /**
   * 显示能匹配上输入框的url列表
   */
  const [autoCompleteOption, setAutoCompleteOption] = useState([]);

  /**
   * form.getFieldsValue()封装层
   */
  const getFormFieldsValue:any = () => {
    let params = form.getFieldsValue();
    if (params["url"]?.indexOf("://") !== -1) {
      params["url"] = params["url"].split("://")[1]
    }
    let newSearchUrlList = []
    if(params.searchUrlList !== undefined && params.searchUrlList.length > 0){
      for(let i = 0; i < params.searchUrlList.length; ++i){
        let searchUrl = params.searchUrlList[i]
        if (searchUrl?.indexOf("://") !== -1) {
          newSearchUrlList.push(searchUrl?.split("://")[1])
        }else {
          newSearchUrlList.push(searchUrl)
        }
      }
      params.searchUrlList = newSearchUrlList;
    }
    console.log(params)
    return paramsChange(params)
  }

  /**
   * 导出
   */
  const exportExcelHandleRun = useRequest(() => exportExcel(getFormFieldsValue()), {
    manual: true,
    onSuccess: (result) => {
      downloadFile(result.id, result.name)
      setExportDisabled(false)
    }
  }).run

  /**
   * 查询提交
   */
  const searchSubmit = () => {
    setSpinning(true)
    // 获取是否汇总
    if(selectedRowKeys != undefined && selectedRowKeys.length > 0){
      form.setFieldsValue({searchUrlList: selectedRowKeys})
    }else {
      form.setFieldsValue({searchUrlList: [form.getFieldValue("url")]})
    }
    let isSum = form.getFieldValue("isSum")
    if (isSum) {
      sumRun()
      sumByCityRun()
    } else {
      sumByDayRun()
      sumByCityAndDayRun()
    }
  }

  /**
   * 获取url列表
   */
  const [allUrlList, setAllUrlList] = useState<{ label: string, value: string }[]>([])
  useRequest(() => allUrl(), {
    onSuccess: (result) => {
      let list: any = []
      result.forEach((url: string) => {
        list.push({label: url, value: url})
      })
      hooksSet(setAllUrlList, list)
    }
  })

  /**
   * 获取子节点
   */
  const [listChildrenList, setListChildrenList] = useState<PageAnalysis[]>([])
  const listChildrenListRun = useRequest(() => listChildren(getFormFieldsValue()), {
    manual: true,
    onSuccess: (result) => {
      hooksSet(setListChildrenList, result, () => {
        fuzzyMatchingActionRef.current?.reload()
        // 清空选中列表
        hooksSet(setSelectedRowKeys, [])
        // 结果列表不为0，默认选中
        if(result?.length !== 0){
          hooksSet(setSelectedRowKeys, [result[0].url], ()=>{
            hooksSet(setSelectedRows, [result[0]], ()=>setListChildrenLoading(false))
          })
        }else {
          setListChildrenLoading(false)
        }
      })
    }
  }).run

  /**
   * 获取总汇总数据
   */
  const sumRun = useRequest(() => sum(getFormFieldsValue()), {
    manual: true,
    onSuccess: (result) => {
      hooksSet(setData, result, () => {
        setSpinning(false)
        actionRef.current?.reload()
        // 隐藏图表
        $("#sumByDayLineEChartsDiv").hide()
        $("#sumByDayBarEChartsDiv").hide()
      })
    }
  }).run

  /**
   * 获取按天汇总数据
   */
  const sumByDayRun = useRequest(() => sumByDay(getFormFieldsValue()), {
    manual: true,
    onSuccess: (result: PageAnalysis[]) => {
      hooksSet(setData, result, () => {
        // 制作折线图需要的数据
        let pvData: { x: any, y: any }[] = []
        let uvData: { x: any, y: any }[] = []
        result.forEach((n) => {
          pvData.push({x: dateFormat(n.date, "yyyy-MM-DD"), y: n.pv})
          uvData.push({x: dateFormat(n.date, "yyyy-MM-DD"), y: n.uv})
        })
        // 生成折线图
        let lineECharts = initECharts("sumByDayLineECharts", getOption({
          type: "line",
          smooth: true,
          dataArray: [
            {legend: "PV", data: pvData},
            {legend: "UV", data: uvData}
          ]
        }))
        // 生成柱状图
        let barECharts = initECharts("sumByDayBarECharts", getOption({
          type: "bar",
          smooth: true,
          dataArray: [
            {legend: "PV", data: pvData},
            {legend: "UV", data: uvData}
          ]
        }))
        $("#sumByDayLineEChartsDiv").show()
        $("#sumByDayBarEChartsDiv").show()
        // 解决width：100%变为100px的情况
        barECharts.resize()
        lineECharts.resize()
        // 刷新表格
        actionRef.current?.reload()
        // 关闭Loading
        setSpinning(false)
      })
    }
  }).run

  /**
   * 按地市汇总
   */
  const sumByCityRun = useRequest(() => sumByCity(getFormFieldsValue()), {
    manual: true,
    onSuccess: (result) => {
      hooksSet(setCityData, result, () => {
        setSpinning(false)
        cityActionRef.current?.reload()
        // 解开查询禁用
        // $(".ant-space-item .ant-btn-primary").removeAttribute("disabled")
      })
    }
  }).run

  /**
   * 按地市和日期汇总
   */
  const sumByCityAndDayRun = useRequest(() => sumByCityAndDay(getFormFieldsValue()), {
    manual: true,
    onSuccess: (result) => {
      hooksSet(setCityData, result, () => {
        setSpinning(false)
        cityActionRef.current?.reload()
      })
    }
  }).run

  useEffect(() => {
    // 隐藏图表
    $("#sumByDayLineEChartsDiv").hide()
    $("#sumByDayBarEChartsDiv").hide()
  }, [])

  // @ts-ignore
  return (
    <PageContainer>
      <Modal
        title="合并地址"
        visible={mergeLinksModelVisible}
        onOk={() => setMergeLinksModelVisible(false)}
        onCancel={() => setMergeLinksModelVisible(false)}
      >
        {selectedRows?.map((n:any, i:number)=><div>{n.title}：{n.url}</div>)}
      </Modal>
      <Modal
        title="链接匹配"
        centered
        visible={modelVisible}
        onOk={() => {
          searchSubmit()
          setModelVisible(false)
        }}
        onCancel={() => setModelVisible(false)}
        width={1000}
      >
        <ProTable
          loading={listChildrenLoading}
          rowKey={"url"}
          pagination={{
            pageSize: 10
            // pageSize: 2
          }}
          rowSelection={{
            selectedRowKeys: selectedRowKeys,
            onSelect:(record, selected, srs)=>{
              if(selected){
                hooksSet(setSelectedRowKeys, [record.url], null, true)
                hooksSet(setSelectedRows, [record], null, true)
              }else {
                let newSelectedRowKeys = selectedRowKeys.slice()
                // @ts-ignore
                newSelectedRowKeys.splice(newSelectedRowKeys.indexOf(record.url), 1)
                hooksSet(setSelectedRowKeys, newSelectedRowKeys)
                hooksSet(setSelectedRows, deleteOfJsonArrays("url", record.url, selectedRows))
              }
            },
            onSelectAll:(selected, srs)=>{
              // 全选改为选择所有页
              if(selected){
                let all:any[] = [];
                listChildrenList?.forEach((n)=>{
                  all.push(n.url)
                })
                hooksSet(setSelectedRowKeys, all)
                hooksSet(setSelectedRows, srs)
              }else {
                hooksSet(setSelectedRowKeys, [])
                hooksSet(setSelectedRows, [])
              }
            }
          }}
          columns={[
            {
              dataIndex: 'title',
              title: '标题',
            },
            {
              dataIndex: 'url',
              title: '页面地址',
              ellipsis: true,
            },
          ]}
          actionRef={fuzzyMatchingActionRef}
          search={false}
          toolBarRender={false}
          request={() => {
            return Promise.resolve({
              data: listChildrenList,
              success: true
            })
          }}
        />
      </Modal>
      <Card>
        <QueryFilter
          defaultColsNumber={100}
          form={form}
          optionRender={(_, __, ___)=>{
            console.log(___)
            return [___[0], <Button type={"primary"} disabled={spinning} onClick={()=>{
              form.validateFields().then(async () => {
                // 判断是否勾选了模糊匹配
                if (form.getFieldValue("fuzzyMatching")) {
                  // 勾选了，则显示获取链接匹配列表，链接匹配弹框
                  setModelVisible(true)
                  setListChildrenLoading(true)
                  listChildrenListRun()
                } else {
                  // 没勾选直接查询
                  searchSubmit()
                }
              })
            }}>查 询</Button>];
          }}
        >
          <Form.Item
            name="url"
            label="页面地址"
            rules={[{required: true}, {validator:(rule, value, callback) => {
                const errors = []
                if(value){
                  if(value.indexOf("http") === 0 && value.indexOf("http://") !== 0 && value.indexOf("https://") !== 0){
                    errors.push(new Error('如果有http开头，则必须http://或https://'))
                  }
                }
                // @ts-ignore
                callback(errors)
              }}]}
            // @ts-ignore
            colSize={9 / 6}
          >
            <AutoComplete
              options={autoCompleteOption}
              onSearch={(searchText: string) => {
                // 去掉前面的http://或https://
                if(searchText.indexOf("://") !== -1){
                  searchText = searchText.split("://")[1];
                }
                // 查询出前10个包含searchText的url
                let result: any = []
                allUrlList.forEach((url) => {
                  if (result.length < 10 && (url.value.indexOf(searchText) != -1)) {
                    result.push(url)
                  }
                })
                setAutoCompleteOption(result)
              }}
            />
          </Form.Item>
          <ProFormDateRangePicker name="dateRange" label="时间范围" rules={[{required: true}]} colSize={5 / 6} fieldProps={{
            format: "YYYYMMDD",
            disabledDate: (currentDate) => currentDate && currentDate > moment(getDateString("yyyyMMdd"), 'YYYYMMDD')
          }}/>
          <Form.Item
            tooltip={"按输入地址模糊匹配查询"}
            label={"模糊匹配"}
            key={"fuzzyMatching"}
            name={"fuzzyMatching"}
            valuePropName={'checked'}
            initialValue={false}
            // @ts-ignore
            colSize={2 / 6}>
            <Checkbox/>
          </Form.Item>
          <Form.Item
            tooltip={"将分日期的查询结果合并为一次结果"}
            label={"合并"}
            key={"isSum"}
            name={"isSum"}
            valuePropName={'checked'}
            initialValue={false}
            // @ts-ignore
            colSize={2 / 6}>
            <Checkbox/>
          </Form.Item>
          <Form.Item key={"current"} name={"current"} hidden={true}/>
          <Form.Item key={"size"} name={"size"} hidden={true}/>
          <Form.Item key={"searchUrlList"} name={"searchUrlList"} hidden={true}/>
        </QueryFilter>
      </Card>
      <Spin spinning={spinning}>
        <div style={{paddingTop: '24px'}}>
          <Card title={"页面访问次数及访问用户（明细）"} extra={<Button type={"primary"} onClick={()=>{
            setExportDisabled(true)
            exportExcelHandleRun()
          }} disabled={exportDisabled}>导出</Button>}>
            <ProTable
              size="small"
              columns={[
                {
                  dataIndex: 'date',
                  title: '日期',
                  renderText: (text) => text === "合并" ? text : dateFormat(text, "yyyy-MM-DD")
                },
                {
                  dataIndex: 'title',
                  title: '标题',
                  renderText: (text) => {
                    // @ts-ignore
                    let searchUrlList = getFormFieldsValue().searchUrlList
                    if (searchUrlList.length <= 1) {
                      // @ts-ignore
                      return text
                    } else {
                      return <Button type="link" style={{padding: 0}}
                                     onClick={() => setMergeLinksModelVisible(true)}>合并</Button>
                    }
                  }
                },
                {
                  dataIndex: 'url',
                  title: '地址',
                  renderText: () => {
                    // @ts-ignore
                    let searchUrlList = getFormFieldsValue().searchUrlList
                    if (searchUrlList.length <= 1) {
                      // @ts-ignore
                      return searchUrlList[0] || getFormFieldsValue().url
                    } else {
                      return <Button type="link" style={{padding: 0}}
                                     onClick={() => setMergeLinksModelVisible(true)}>合并</Button>
                    }
                  }
                },
                {
                  dataIndex: 'pv',
                  title: 'PV',
                  width: 100
                },
                {
                  dataIndex: 'uv',
                  title: 'UV',
                  width: 100
                }
              ]}
              actionRef={actionRef}
              pagination={{
                pageSize: 10
              }}
              search={false}
              toolBarRender={false}
              request={() => {
                return Promise.resolve({
                  data: data,
                  success: true
                })
              }}
            />
          </Card>
        </div>
        <div id={"sumByDayLineEChartsDiv"} style={{paddingTop: '24px'}}>
          <Card title={"页面访问次数及访问用户（折线图）"}>
            <div style={{width: "100%", height: "400px"}} id={"sumByDayLineECharts"}></div>
          </Card>
        </div>
        <div id={"sumByDayBarEChartsDiv"} style={{paddingTop: '24px'}}>
          <Card title={"页面访问次数及访问用户（柱状图）"}>
            <div style={{width: "100%", height: "400px"}} id={"sumByDayBarECharts"}></div>
          </Card>
        </div>
        <div style={{paddingTop: '24px'}}>
          <Card title={"页面访问次数及访问用户（按地市）"}>
            <ProTable
              size="small"
              bordered
              columns={[
                {
                  dataIndex: 'date',
                  title: '日期',
                  renderText: (text) => text === "合并" ? text : dateFormat(text, "yyyy-MM-DD")
                },
                {
                  title: 'UV',
                  children: [
                    {
                      dataIndex: 'ncUv',
                      title: '鹰潭',
                      renderText: (_, record: any) => record.cityUv[0]
                    },
                    {
                      dataIndex: 'jjUv',
                      title: '新余',
                      renderText: (_, record: any) => record.cityUv[1]
                    },
                    {
                      dataIndex: 'jdzUv',
                      title: '南昌',
                      renderText: (_, record: any) => record.cityUv[2]
                    },
                    {
                      dataIndex: 'srUv',
                      title: '九江',
                      renderText: (_, record: any) => record.cityUv[3]
                    },
                    {
                      dataIndex: 'ycUv',
                      title: '上饶',
                      renderText: (_, record: any) => record.cityUv[4]
                    },
                    {
                      dataIndex: 'xyUv',
                      title: '抚州',
                      renderText: (_, record: any) => record.cityUv[5]
                    },
                    {
                      dataIndex: 'pxUv',
                      title: '宜春',
                      renderText: (_, record: any) => record.cityUv[6]
                    },
                    {
                      dataIndex: 'gzUv',
                      title: '吉安',
                      renderText: (_, record: any) => record.cityUv[7]
                    },
                    {
                      dataIndex: 'ncUv',
                      title: '赣州',
                      renderText: (_, record: any) => record.cityUv[8]
                    },
                    {
                      dataIndex: 'ncUv',
                      title: '景德镇',
                      renderText: (_, record: any) => record.cityUv[9]
                    },
                    {
                      dataIndex: 'ncUv',
                      title: '萍乡',
                      renderText: (_, record: any) => record.cityUv[10]
                    },
                  ]
                },
                {
                  title: 'PV',
                  children: [
                    {
                      dataIndex: 'ncPv',
                      title: '鹰潭',
                      renderText: (_, record: any) => record.cityPv[0]
                    },
                    {
                      dataIndex: 'jjPv',
                      title: '新余',
                      renderText: (_, record: any) => record.cityPv[1]
                    },
                    {
                      dataIndex: 'jdzPv',
                      title: '南昌',
                      renderText: (_, record: any) => record.cityPv[2]
                    },
                    {
                      dataIndex: 'srPv',
                      title: '九江',
                      renderText: (_, record: any) => record.cityPv[3]
                    },
                    {
                      dataIndex: 'ycPv',
                      title: '上饶',
                      renderText: (_, record: any) => record.cityPv[4]
                    },
                    {
                      dataIndex: 'xyPv',
                      title: '抚州',
                      renderText: (_, record: any) => record.cityPv[5]
                    },
                    {
                      dataIndex: 'pxPv',
                      title: '宜春',
                      renderText: (_, record: any) => record.cityPv[6]
                    },
                    {
                      dataIndex: 'gzPv',
                      title: '吉安',
                      renderText: (_, record: any) => record.cityPv[7]
                    },
                    {
                      dataIndex: 'ncPv',
                      title: '赣州',
                      renderText: (_, record: any) => record.cityPv[8]
                    },
                    {
                      dataIndex: 'ncPv',
                      title: '景德镇',
                      renderText: (_, record: any) => record.cityPv[9]
                    },
                    {
                      dataIndex: 'lcPv',
                      title: '萍乡',
                      renderText: (_, record: any) => record.cityPv[10]
                    },
                  ]
                }
              ]}
              actionRef={cityActionRef}
              pagination={{
                pageSize: 10
              }}
              search={false}
              toolBarRender={false}
              request={() => {
                return Promise.resolve({
                  data: cityData,
                  success: true
                })
              }}
            />
          </Card>
        </div>
      </Spin>
    </PageContainer>
  )
}

export default PageAnalysisTools;
